<?php

namespace App\Console\Commands;

use DiDom\Document;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Illuminate\Console\Command;

class ysx8 extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ysx8';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $host = 'http://localhost:4444/wd/hub';
        $base = 'https://www.ysts8.net';
        $url = $base . '/Yshtml/Ys6751.html';
        $html = file_get_contents($url);
        $document = new Document($html);
        $rs = $document->first('.ny_l')->find('ul>li>a');
        $chrome = DesiredCapabilities::chrome();
        $chrome->setCapability('moz:chromeOptions', ['args' => ['-headless', '--disable-gpu']]);
        $driver = RemoteWebDriver::create($host, $chrome);
        foreach ($rs as $item) {
            $name = '明朝那些事' . $item->text();
            echo "正在下载$name\n";
            $this->loadMp3($base . $item->attr('href'), $name, $driver);
        }
        $driver->quit();
        die();
    }

    private function loadMp3($url, $name,RemoteWebDriver $driver, $time = 0)
    {
        $driver->get($url);
        $driver->switchTo()->frame($driver->findElement(WebDriverBy::tagName('iframe')));
        $driver->wait()->until(
            WebDriverExpectedCondition::presenceOfElementLocated(WebDriverBy::id('jp_audio_0'))
        );
        $src = $driver->findElement(WebDriverBy::id('jp_audio_0'))->getAttribute('src');
        $rs = file_get_contents($src);
        if ($rs) {
            file_put_contents('mp3/' . $name . '.mp3', $rs);
        } elseif ($time > 2) {
            echo "$name 下载失败次数大于3次 跳过\n";
        } else {
            $time += 1;
            echo "重新下载$name-$time\n";
            $this->loadMp3($url, $name, $driver, $time);
        }
    }
}
